import 'dart:convert';
import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/order_history.dart';
import '../../util/app_util.dart';
// import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';

class OrderHistoryMainScreen extends StatefulWidget {
  OrderHistoryMainScreen({Key? key}) : super(key: key);
  _OrderHistoryMainScreenState createState() => _OrderHistoryMainScreenState();
}

class _OrderHistoryMainScreenState extends State<OrderHistoryMainScreen>
    with AfterLayoutMixin<OrderHistoryMainScreen>, WidgetsBindingObserver {
  late OrderHistBloc listSourceRepository;

  @override
  void initState() {
    super.initState();
    listSourceRepository = new OrderHistBloc();
    listSourceRepository.criteria = {};
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      switch (state) {
        case AppLifecycleState.resumed:
          print('resumed');
          listSourceRepository.refresh();
          // Handle this case
          break;
        case AppLifecycleState.inactive:
          print('inactive');
          // Handle this case
          break;
        case AppLifecycleState.paused:
          print('paused');
          // Handle this case
          break;
        case AppLifecycleState.detached:
          print('detached');
          // TODO: Handle this case.
          break;
      }
    });
  }

  @override
  void dispose() {
    listSourceRepository.dispose();
    super.dispose();
  }

  @override
  void afterFirstLayout(BuildContext context) {
    if ((AppSession.authortoken ?? '').isEmpty)
      App.router.navigateTo(context, AppRoutes.loginSignin);
    else {
      // if ((listSourceRepository.popup_window['title'] ?? '').isNotEmpty)
      //   showDialog(context: context, builder: (_) => _popup_ads(context));
    }
  }

  // Widget _popup_ads(BuildContext context) {
  //   return Dialog(
  //     child: Container(
  //       width: 300.w,
  //       height: (550 * 3).h,
  //       color: Colors.black54,
  //       child: Column(
  //           mainAxisAlignment: MainAxisAlignment.start,
  //           crossAxisAlignment: CrossAxisAlignment.center,
  //           children: <Widget>[
  //             Container(
  //               width: 300.w,
  //               height: 500.h,
  //               decoration: BoxDecoration(
  //                   image: DecorationImage(
  //                       image: CachedNetworkImageProvider(
  //                         AppUtil.popup_window['image_info']['url'],
  //                       ),
  //                       fit: BoxFit.cover)),
  //             ),
  //             FlatButton(
  //               onPressed: () {
  //                 Navigator.of(context, rootNavigator: true).pop('dialog');
  //               },
  //               padding: EdgeInsets.all(0.0),
  //               child: Image.asset('assets/main/close-circle.png'),
  //             ),
  //           ]),
  //     ),
  //   );
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        brightness: Brightness.light,
        title: Text(
          '我的订单',
          style: TextStyle(
            fontSize: 16.sp,
            color: AppColor.blackMain,
          ),
        ),
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
      ),
      body: PullToRefreshNotification(
        color: Colors.transparent,
        onRefresh: () => listSourceRepository.refresh(),
        maxDragOffset: 80.0,
        child: LoadingMoreCustomScrollView(
          physics: AlwaysScrollableClampingScrollPhysics(),
          slivers: <Widget>[
            // SliverAppBar(
            //   brightness: Brightness.light,
            //   title: Text(
            //     '我的订单',
            //     style: TextStyle(
            //       fontSize: 16.sp,
            //       color: AppColor.blackMain,
            //     ),
            //   ),
            //   automaticallyImplyLeading: false,
            //   backgroundColor: Colors.white,
            // ),
            PullToRefreshContainer(buildPulltoRefreshHeader),

            LoadingMoreSliverList(
              SliverListConfig<Map>(
                itemBuilder: _OrderHistoryMainScreenState.orderCard,
                sourceList: listSourceRepository,
//                    showGlowLeading: false,
//                    showGlowTrailing: false,
                padding: EdgeInsets.all(0.0),
                // collectGarbage: (List<int> indexes) {
                //   ///collectGarbage
                //   indexes.forEach((index) {
                //     final item = listSourceRepository[index];
                //   });
                // },
                // viewportBuilder: (int firstIndex, int lastIndex) {
                //   // print("viewport : [$firstIndex,$lastIndex]");
                // },
              ),
            ),
            // ),
          ],
        ),
      ),
    );
  }

  Widget buildPulltoRefreshHeader(PullToRefreshScrollNotificationInfo? info) {
    //print(info?.mode);
    //print(info?.dragOffset);
    //    print("------------");
    var offset = info?.dragOffset ?? 0.0;
    var mode = info?.mode;
    Widget? refreshWiget = Container();
    //it should more than 18, so that RefreshProgressIndicator can be shown fully
    if (info?.refreshWidget != null && offset > 18.0 && mode != RefreshIndicatorMode.error) {
      refreshWiget = info?.refreshWidget;
    }

    Widget child;
    if (mode == RefreshIndicatorMode.error) {
      child = GestureDetector(
          onTap: () {
            // refreshNotification;
            info?.pullToRefreshNotificationState?.show();
          },
          child: Container(
            color: Colors.grey,
            alignment: Alignment.bottomCenter,
            height: offset,
            width: double.infinity,
            //padding: EdgeInsets.only(top: offset),
            child: Container(
              padding: EdgeInsets.only(left: 5.0),
              alignment: Alignment.center,
              child: Text(
                (mode??'').toString() + "  click to retry",
                style: TextStyle(fontSize: 12.0, inherit: false),
              ),
            ),
          ));
    } else {
      child = Container(
        color: AppColor.yellowMain,
        alignment: Alignment.bottomCenter,
        height: offset,
        width: double.infinity,
        //padding: EdgeInsets.only(top: offset),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            refreshWiget!,
            Container(
              padding: EdgeInsets.only(left: 5.0),
              alignment: Alignment.center,
              child: Text(
                // mode?.toString() ?? "",
                "拼命加载中.....",
                style: TextStyle(fontSize: 12.0, inherit: false),
              ),
            )
          ],
        ),
      );
    }

    return SliverToBoxAdapter(
      child: child,
    );
  }

  static Widget orderCard(BuildContext context, Map item, int index) {
    // final _stripePayment = FlutterStripePayment();
    CancelFunc cancelLoading;

    stripeInit() async {
      // await _stripePayment.setStripeSettings(App3rdKey.stripe_key, App3rdKey.applepay_id);
      // print(_stripePayment);
    }

    stripeInit();
    return Card(
      elevation: 5,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          // var lv_detail = Uri.encodeQueryComponent(jsonEncode(item));
          // App.router.navigateTo(context, 'history_detail?detail=${lv_detail}');
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 20.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  _normalText(
                    "# " + item['oid'].toString(),
                  ),
                  _statusText(
                    item['status_desc'],
                    AppColor.getOrderColor(item['status']),
                  ),
                ],
              ),
              Container(
                margin: EdgeInsets.symmetric(
                  vertical: 10.h,
                ),
                child: Divider(
                  height: 1,
                  color: Colors.grey,
                  indent: 0,
                  endIndent: 0,
                ),
              ),
              _normalText(
                '配送时间: ' + item['dl_date'] + '  ' + item['dl_window'],
              ),
              _normalText(
                '总共 ' + item['items'].length.toString() + ' 件货品',
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  _normalText(
                    '总价: \$' + item['charge_total'].toString(),
                  ),
                  GestureDetector(
                    onTap: () {
                      var lv_detail = Uri.encodeQueryComponent(jsonEncode(item));
                      App.router
                          .navigateTo(context, AppRoutes.historyDetail + '?detail=${lv_detail}');
                    },
                    child: _statusText('查看详情', Colors.blue),
                  ),
                ],
              ),
              if (item['status'] == 0)
                ElevatedButton(
                  style:ButtonStyle(
                    textStyle:MaterialStateProperty.all(TextStyle(color: Colors.white)),
                    // color: Color(0xffFF3434),
                    // textColor: Colors.white,
                  ),
                  onPressed: () async {
                    var lv_detail = Uri.encodeQueryComponent(jsonEncode(item));
                    App.router
                        .navigateTo(context, AppRoutes.historyDetail + '?detail=${lv_detail}');
                    // Map<String, dynamic> lm_param = {"oid": item['oid']};
                    // final apputil = AppUtil();
                    // var lm_result = await apputil.orderRepay(lm_param);
                    // var lv_pmid = '';
                    // if ((lm_result ?? {}).isNotEmpty) {
                    //   if ((lm_result['ev_error'] == 0) &&
                    //       ((lm_result['ev_result'] ?? {}).isNotEmpty)) {
                    //     lv_pmid = AppSession.creditcard['pmid'];

                    //     cancelLoading = BotToast.showLoading(duration: Duration(seconds: 10));
                    //     AppPopupService.showAlertSimple('W', '准备支付', '加载中.....',
                    //         iv_duration: Duration(seconds: 1));
                    //     var intentResponse = await _stripePayment.confirmPaymentIntent(
                    //         lm_result['ev_result']['payment_intent'],
                    //         lv_pmid,
                    //         lm_result['ev_result']['charge_total'],
                    //         true);
                    //     switch (intentResponse.status) {
                    //       case PaymentResponseStatus.succeeded:
                    //         {
                    //           cancelLoading();
                    //           AppSession.bottomIndex = 0;
                    //           AppPopupService.showAlertSimple(
                    //             'S',
                    //             '下单成功',
                    //             '请刷新历史订单查看状态',
                    //           );

                    //           print(intentResponse.paymentIntentId);
                    //           print(intentResponse);
                    //         }
                    //         break;
                    //       case PaymentResponseStatus.failed:
                    //         {
                    //           cancelLoading();
                    //           print(intentResponse);
                    //           break;
                    //         }
                    //       default:
                    //         {
                    //           cancelLoading();
                    //           print(intentResponse);
                    //         }
                    //         break;
                    //     }
                    //   }
                    // }
                  },
                  child: Container(
                    child: Text(
                      '重新支付',
                      style: TextStyle(color: Colors.white, fontSize: 15.sp),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  static Widget _normalText(
    String iv_str, {
    int fontSize = 15,
  }) {
    return Text(
      iv_str,
      softWrap: true,
      overflow: TextOverflow.fade,
      style: TextStyle(
        fontSize: fontSize.sp,
        color: AppColor.blackMain,
      ),
    );
  }

  static Widget _statusText(
    String iv_str,
    Color iv_color, {
    int fontSize = 15,
  }) {
    return Text(
      iv_str,
      softWrap: true,
      overflow: TextOverflow.fade,
      style: TextStyle(
        fontSize: fontSize.sp,
        color: iv_color,
      ),
    );
  }
}
